package com.steven.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

public class HttpHandler extends SimpleChannelInboundHandler<HttpObject> {
    /**
     * 读取客户端数据
     * @param context
     * @param httpObject 客户端和服务器端相互通讯的数据被封装成httpObject
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext context, HttpObject httpObject) throws Exception {
        if(httpObject instanceof HttpRequest){

            String uri = ((HttpRequest) httpObject).getUri();
            if(("/favicon.ico").equals(uri)){
                System.out.println("该请求不做响应");
                return;
            }

            System.out.println("客户端地址："+context.channel().remoteAddress());
            //回复信息给浏览器
            ByteBuf content = Unpooled.copiedBuffer("connecting ok", CharsetUtil.UTF_8);
            //构造http对象响应
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,content);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());
            //发送响应数据
            context.writeAndFlush(response);
        }
    }
}
